<?php
namespace common\models;

use common\validate\BaseValidate;
use Yii;
use yii\base\Model;

/**
 * Login form
 */
class ChangePassForm extends BaseValidate
{
    public $phone;
    public $oldpassword;
    public $newpassword;
    public $repassword;
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['oldpassword','newpassword','repassword'], 'required'],
            // password is validated by validatePassword()
            ['oldpassword', 'validatePassword' , 'message' => '旧密码输入错误'],   //检测原密码是否正确
            ['newpassword', 'compare', 'compareAttribute'=>'repassword' , 'message'=>'两次密码输入不一致'], //检测两次输入密码是否一致
        ];
    }

    public function attributeLabels()
    {
        return [
//            'code' => '验证码',
            'newpassword' => '新密码',
            'repassword' =>  '确认密码',
            'oldpassword' => '原登录密码',
        ];
    }


    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->oldpassword)) {
                $this->addError($attribute, '原密码输入错误');
            }
        }
    }


    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->phone);
        }
        return $this->_user;
    }
}
